package longfly.development;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker.OnTimeChangedListener;

public class Sell_Rank extends Activity{

	SQLiteDatabase db;
    private ArrayList<HashMap<String,String>> list=null;
    private HashMap<String,String>map=null;
	SimpleAdapter adapter;

	/********以下是对话框内的控件**************************/
	Button		DIALOG_BTN_OK;
	Button		DIALOG_BTN_CANCEL;
	TextView	DIALOG_TX_TIME;	
	DatePicker  DIALOG_DATEPICKER;
	TimePicker  DIALOG_TIMEPICKER;
	/****************************************************/	
	Button	LIUSHUI_CHECKE,LIUSHUI_EXIT,LIUSHUI_START,LIUSHUI_END;
	ListView	LS_LIUSHUI;
	TextView	TITLE,TEXT_1;
	LinearLayout LNEARLAYOUT;
	String SQL_Table = "lfcy_base_sellinf";
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.i800_liushui_check);
        
       find_id();
       key_things();
 	   db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/Android_POS.db3", null);
 	   LNEARLAYOUT.setVisibility(View.VISIBLE);
 	   TITLE.setText("菜品销售排行");
 	   TEXT_1.setText("上次时段选择：");
	}

	private void key_things() {
		// TODO Auto-generated method stub
		LIUSHUI_CHECKE.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		//启动新线程
				progressDialog("正在处理销售数据 ", "请稍等......");		
		     	insert_Thread thread= new insert_Thread();
		     	thread.start();	
		   		//启动对话框
		   		//处理计算时间段内的所有菜品销售数据
		   		//汇总，生成新的表
		   		//在列表显示出来			
			}
	    });	
		LIUSHUI_EXIT.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		db.close();
		   		finish();
		   	}
	    });	
		LIUSHUI_START.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		START_END = true;
                showDialog(DIALOG_FIND);
		   	}
	    });			
		LIUSHUI_END.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		START_END = false;
                showDialog(DIALOG_FIND);
		   	}
	    });	
		
		LS_LIUSHUI.setOnItemClickListener(new OnItemClickListener() {
			@Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id)
			{
				//变蓝就好
			}
		});		
	}

	//创建并新建一个Hashmap
	private ArrayList fill_hashmap(Cursor cursor) {
	    list=new ArrayList<HashMap<String,String>>();
		int i=0;
		while(cursor.moveToNext()) {
			i++;
            map=new HashMap<String,String>();
            
            map.put("_id", cursor.getString(cursor.getColumnIndex("_id")));
            map.put("_num", ""+i);
            map.put("cDishName", cursor.getString(cursor.getColumnIndex("cDishName")));
            map.put("cDishCode",  cursor.getString(cursor.getColumnIndex("cDishCode")));
            map.put("fDishPrice",  cursor.getString(cursor.getColumnIndex("fDishPrice")));
            map.put("cDishQty",  cursor.getString(cursor.getColumnIndex("cDishQty")));
            map.put("cDishUnitName",  cursor.getString(cursor.getColumnIndex("cDishUnitName")));
            map.put("cDishUnitCode",  cursor.getString(cursor.getColumnIndex("cDishUnitCode")));
            map.put("fDishAllPrice",  cursor.getString(cursor.getColumnIndex("fDishAllPrice")));
			list.add(map);
		}
		
		return list;
	}
	
	private void inflateList(Cursor cursor)
	{
		//将数据与adapter集合起来
        adapter = new SimpleAdapter(
        		this, 
				list, 
				R.layout.imx_timesell_rank 
				, new String[]{	"_num" 			, 
						"cDishName"		,"cDishCode"		, "fDishPrice"	,
						"cDishQty" ,"cDishUnitName"	,"fDishAllPrice" 
			}
        		, new int[]{R.id.text_1 , R.id.text_2 ,R.id.text_3,R.id.text_4,R.id.text_5,R.id.text_6,R.id.text_7
			}
        );
		
		//显示数据
        LS_LIUSHUI.setAdapter(adapter);
	}
	
	private void find_id() {
		// TODO Auto-generated method stub
		LIUSHUI_CHECKE 	= (Button) findViewById(R.id.liuchui_check_chaxun);
		LIUSHUI_EXIT 	= (Button) findViewById(R.id.liuchui_check_exit);
		LIUSHUI_START 	= (Button) findViewById(R.id.liuchui_check_start);
		LIUSHUI_END 	= (Button) findViewById(R.id.liuchui_check_end);
		LS_LIUSHUI		= (ListView) findViewById(R.id.liushui_check_list);
		TITLE			= (TextView) findViewById(R.id.liushui_title);
		TEXT_1			= (TextView) findViewById(R.id.liushui_text_1);
		LNEARLAYOUT		= (LinearLayout) findViewById(R.id.liushui_style_5);
	}
	
	/***      初始化时间对话框！ 命名为buildDialog      ***/
   	int	now_year,now_month,now_day,now_hour,now_minute;
	int sYear,sMounth,sDay,sHour,sMinute;	//起始时间记录，和起始按钮的时间要一致
	int eYear,eMounth,eDay,eHour,eMinute;	//结束时间记录，和结束按钮的时间要一致
	boolean	Init_Dialog_S = true;
	boolean	Init_Dialog_E = true;
	boolean	START_END;
   	private int DIALOG_FIND=101;
	private Dialog buildDialog(Context context) {  	
		// TODO Auto-generated method stub
        final AlertDialog.Builder builder =   new AlertDialog.Builder(context);  
        //下面是设置对话框的属性
        builder.setIcon(R.drawable.other_1); 
        if (START_END) {
            builder.setTitle("选择起始时间");  
		} else {
	        builder.setTitle("选择结束时间");  
		}
        LayoutInflater inflater = LayoutInflater.from(Sell_Rank.this);
        View view = inflater.inflate(R.layout.i800dialog_datetime_choose, null);			
        
		if (START_END) {
			if (Init_Dialog_S) {
	            Calendar calc = Calendar.getInstance();
	            now_year  = calc.get(Calendar.YEAR);
	            now_month = calc.get(Calendar.MONTH);
	            now_day   = calc.get(Calendar.DAY_OF_MONTH);
	            now_hour  = calc.get(Calendar.HOUR_OF_DAY);
	            now_minute= calc.get(Calendar.MINUTE);						
			} else {
	            now_year  = sYear;
	            now_month = sMounth;
	            now_day   = sDay;
	            now_hour  = sHour;
	            now_minute= sMinute;
			}
		} else {
			if (Init_Dialog_E) {
	            Calendar calc = Calendar.getInstance();
	            now_year  = calc.get(Calendar.YEAR);
	            now_month = calc.get(Calendar.MONTH);
	            now_day   = calc.get(Calendar.DAY_OF_MONTH);
	            now_hour  = calc.get(Calendar.HOUR_OF_DAY);
	            now_minute= calc.get(Calendar.MINUTE);						
			} else {
	            now_year  = eYear;
	            now_month = eMounth;
	            now_day   = eDay;
	            now_hour  = eHour;
	            now_minute= eMinute;
			}
		}

        builder.setView(view);
        builder.setCancelable(false);
        
		DIALOG_BTN_OK 		= (Button) view.findViewById(R.id.dialog_time_ok);
		DIALOG_BTN_CANCEL 	= (Button) view.findViewById(R.id.dialog_time_cancel);	
		DIALOG_TX_TIME		= (TextView) view.findViewById(R.id.dialog_time_tx);
		DIALOG_TIMEPICKER	= (TimePicker) view.findViewById(R.id.dialog_time_pick);
		DIALOG_DATEPICKER	= (DatePicker) view.findViewById(R.id.dialog_date_pick);
		
		//默认时间格式为12小时制的，这里我们改成24小时的制
		DIALOG_TIMEPICKER.setIs24HourView(true);
		DIALOG_TIMEPICKER.setCurrentHour(now_hour);
		DIALOG_TIMEPICKER.setCurrentMinute(now_minute);	
		
		DIALOG_DATEPICKER.init(now_year, now_month, now_day, new OnDateChangedListener() {
			@Override
			public void onDateChanged(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				// TODO Auto-generated method stub
				now_year  = year;
				now_month = monthOfYear;
				now_day   = dayOfMonth;		
			}
		});
		
		DIALOG_TIMEPICKER.setOnTimeChangedListener(new OnTimeChangedListener() {		
			@Override
			public void onTimeChanged(TimePicker view, int hour, int minute) {
				// TODO Auto-generated method stub
				now_hour = hour;
				now_minute = minute;
			}
		});
		
		DIALOG_BTN_OK.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
				if (START_END) {
		              sYear		=	now_year;
		              sMounth	=	now_month;
		              sDay		=	now_day;
		              sHour		=	now_hour;
		              sMinute	=	now_minute;
		              showData(sYear,sMounth+1,sDay,sHour,sMinute);
				} else {
		              eYear		=	now_year;
		              eMounth	=	now_month;
		              eDay		=	now_day;
		              eHour		=	now_hour;
		              eMinute	=	now_minute;
		              showData(eYear,eMounth+1,eDay,eHour,eMinute);
				}
				if (START_END) {
					Init_Dialog_S = false;					
				} else {
					Init_Dialog_E = false;
				}
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
		   	}
	    });
		
		DIALOG_BTN_CANCEL.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		removeDialog(DIALOG_FIND);  //关闭对话框 
		   	}
	    });
		
        return builder.create();  
    } 
    
	protected void showData(int year2, int month2, int day2, int hour2,
			int minute2) {
		// TODO Auto-generated method stub
		String mMounth,mDay,mHour,mMinute;
		
		if (month2<10) {
			mMounth = "0"+month2;
		}else {
			mMounth = ""+month2;
		}
		
		if (day2<10) {
			mDay = "0"+day2;
		}else {
			mDay = ""+day2;
		}
		if (hour2<10) {
			mHour = "0"+hour2;
		}else {
			mHour = ""+hour2;
		}	
		if (minute2<10) {
			mMinute = "0"+minute2;
		}else {
			mMinute = ""+minute2;
		}		
		DIALOG_TX_TIME.setText("您设置的时间是:         "+year2+"年"+ mMounth+"月"+
				mDay+"日"+mHour+"点"+mMinute+"分");
		
   		if (START_END) {
   			LIUSHUI_START.setText( year2+"-"+mMounth+"-"+mDay +" "+mHour+":"+mMinute );
		} else {
			LIUSHUI_END.setText( year2+"-"+mMounth+"-"+mDay +" "+mHour+":"+mMinute );
		}
	}

	@Override 
    protected Dialog onCreateDialog(int id) {  
        // TODO Auto-generated method stub  
        if(id==101){  
        	return this.buildDialog(Sell_Rank.this);  
        }
        else{  
            return null;  
        }  
    } 

    @Override 
    protected void onPrepareDialog(int id, Dialog dialog) {  
        // TODO Auto-generated method stub  
        super.onPrepareDialog(DIALOG_FIND, dialog);  
    } 
    /***      以上是初始一个对话框！       ***/	  

    //插入数据
    //清空数据
    
	
	/***************     以下是一个带进度条的对话框    **************************************/
	ProgressDialog progressDialog;
	private void progressDialog(String title, String message) {
		// TODO Auto-generated method stub
	     progressDialog = new ProgressDialog(Sell_Rank.this);
	     progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	     progressDialog.setMessage(message);
	     progressDialog.setTitle(title);
	     progressDialog.setProgress(0);
	     progressDialog.setMax(100);
	     progressDialog.setCancelable(false);
	     progressDialog.show();
	}

	//用来查询进度条的值！大于100就把进度条Cancel掉
    Handler handler = new Handler(){
    	  @Override
    	  public void handleMessage(Message msg) {
    		  // TODO Auto-generated method stub
    		  if(msg.what>=100){
    			  progressDialog.cancel();
				  Cursor  cursor = db.rawQuery("select * from lfcy_sell_rank_linshi order by cDishQty DESC",null);
				  fill_hashmap(cursor);
				  inflateList(cursor);	
    	       }
    		  progressDialog.setProgress(msg.what);
    		  super.handleMessage(msg);
    	  }
    };

	
//创建一个进程！用来后台加载数据
    class insert_Thread extends Thread{
        public void run(){
			handler.sendEmptyMessage(1);	//进度条进度

	   		try {
	   			db.delete("lfcy_sell_rank_linshi",  "_id >?", new String[]{"0"});
   			} catch (Exception e) {
				System.out.println("delete failled");					
   			}
  			
	   	   	String start_time,end_time;
	   	   	start_time = LIUSHUI_START.getText().toString();
	   	   	end_time = LIUSHUI_END.getText().toString();
	   		String[] refer = {start_time , end_time};
			Cursor  cursor = db.rawQuery("select * from "+SQL_Table+" where dXiadantime > ? and dXiadantime < ? ",refer);
			//获取到了时间段内所有菜品
			while(cursor.moveToNext()) {
				String item  = cursor.getString(cursor.getColumnIndex("cDishCode"));
	   			sql_control sqlc = new sql_control();					
				boolean if_only_one = sqlc.sql_item_only_one(db, "lfcy_sell_rank_linshi", "cDishCode", item);
				//先判断这个菜是不是有了！
				if (if_only_one) {
					//没有重复
					//获取数量
			   	    Integer Dishnum = new Integer(cursor.getString(cursor.getColumnIndex("cDishQty")));
					//获取总价格
			   	    float DishAllPrice = Float.parseFloat(cursor.getString(cursor.getColumnIndex("fDishPrice")));
					//得到单价
			   	    float DishPrice = DishAllPrice/Dishnum;
					//插入数据
					db.execSQL("insert into lfcy_sell_rank_linshi values(null,?,?,?,?,?,?,?,?,null)", 
							new String[]{
						cursor.getString(cursor.getColumnIndex("cDishName")) ,
						cursor.getString(cursor.getColumnIndex("cDishCode")) ,	
						"" + DishPrice ,
						cursor.getString(cursor.getColumnIndex("cDishQty")) ,
						cursor.getString(cursor.getColumnIndex("cDishUnitName")) ,
						cursor.getString(cursor.getColumnIndex("cDishUnitCode")) ,
						cursor.getString(cursor.getColumnIndex("fDishPrice")) ,
						"1001"  });
				} else {
					//重复了
					//updata数据
			   		try {
			   			ContentValues cv = new ContentValues();
			   		   	//存储修改的数据
			   		   	cv.put("cDishName" 		, cursor.getString(cursor.getColumnIndex("cDishName")));
			   		   	cv.put("cDishCode" 		, cursor.getString(cursor.getColumnIndex("cDishCode")));
			   		   	cv.put("fDishPrice" 	, cursor.getString(cursor.getColumnIndex("fDishPrice")) );
			   		   	cv.put("cDishUnitName" 	, cursor.getString(cursor.getColumnIndex("cDishUnitName")) );
			   		   	cv.put("cDishUnitCode" 	, cursor.getString(cursor.getColumnIndex("cDishUnitCode")) );
			   		   	String[] fuck = {item};
			   		    Cursor cursor2 = db.rawQuery("select * from lfcy_sell_rank_linshi where cDishCode = ?",fuck);

			   		    String recorsend = "null",price_thiscaiist = "null";
			   		    while(cursor2.moveToNext()) {
							recorsend  = cursor2.getString(cursor2.getColumnIndex("cDishQty"));
							price_thiscaiist  = cursor2.getString(cursor2.getColumnIndex("fDishAllPrice"));
						}
				   	    Integer intObjj = new Integer(recorsend);
				   	    int qty_i = intObjj	;	//刚才已有的  
				   	    float qty_f = Float.parseFloat(price_thiscaiist);
				   	    
				   		Integer intObj = new Integer(cursor.getString(cursor.getColumnIndex("cDishQty")));
				   	    int qty_j = intObj;		//新的一条
				   	    float qty_k = Float.parseFloat(cursor.getString(cursor.getColumnIndex("fDishPrice")));

			   		   	cv.put("cDishQty" 		, qty_i + qty_j );
			   		   	cv.put("fDishAllPrice" 	, qty_f + qty_k );
			   		   	cv.put("fDishPrice" 	, (qty_f + qty_k)/(qty_i + qty_j));
			   		   	String[] contion = {item}; 			   		   	
					   	db.update("lfcy_sell_rank_linshi",cv,"cDishCode = ? ",contion);
			   		} catch (Exception e) {
						System.out.println("update failed");					   									
			   		}	
				}

			}			
			//汇总生成新的菜品销售报表
			

			
			handler.sendEmptyMessage(100);
        }
    };
	
	/***************     以上是一个进度条    **************************************/

    
}
